package com.ding.easycontroller.controller;

import com.ding.easycontroller.model.R;
import com.ding.easycontroller.pojo.DaoUpdateOrAddVO;
import com.ding.easycontroller.pojo.ServiceBrief;
import com.ding.easycontroller.pojo.ServiceDetails;
import com.ding.easycontroller.service.DaoService;
import com.ding.easycontroller.work.Dao;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

@RestController
@RequestMapping("/_config/dao")
public class _Dao {

    @Autowired
    private DaoService daoService;

    @PostMapping("/remove")
    public R remove(@RequestParam String id) throws IOException {
        daoService.removeById(id);
        return R.OK;
    }

    @PostMapping("/updateOrAdd")
    public R updateOrAdd(@Validated DaoUpdateOrAddVO daoUpdateVO) throws IOException {
        Dao dao = new Dao();
        BeanUtils.copyProperties(daoUpdateVO, dao);
        daoService.updateOrAdd(dao);
        return R.ok(dao.getId());
    }

    @GetMapping("/get")
    R get(@RequestParam String id) {
        Dao dao = daoService.getById(id);
        if (dao == null) {
            return R.NotFound;
        }
        ServiceDetails daoDetails = new ServiceDetails();
        BeanUtils.copyProperties(dao, daoDetails);
        return R.ok(daoDetails);
    }


    @GetMapping("/all")
    R all() {
        List<Dao> daos = daoService.listAll();
        List<ServiceBrief> daoBriefs = new ArrayList<>();
        for (Dao dao : daos) {
            ServiceBrief daoBrief = new ServiceBrief();
            BeanUtils.copyProperties(dao, daoBrief);
            daoBriefs.add(daoBrief);
        }
        return R.ok(daoBriefs);
    }


}

